package com.lin.testutil.testpdfutil;

import com.itextpdf.text.Font;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.lin.util.FileWriteUtil;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.junit.Test;

import javax.imageio.ImageIO;
import java.awt.Image;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 生成pdf并盖章
 *
 * @author linqiankun
 */
public class GenPdf {

    int dataNums = 120;
    private static final String p = "temp/";

    /**
     * test pass
     *
     * @throws FileNotFoundException
     */
    @Test
    public void test1() throws FileNotFoundException {//生成pdf
//        FileOutputStream outputStream = new FileOutputStream("a.pdf");

        ByteArrayOutputStream b = new ByteArrayOutputStream();
        Document document = new Document();
        try {
            PdfCopy.getInstance(document, b);
            document.setPageSize(PageSize.A4);
            document.open();

            // 文字部分
            BaseFont bfTitle;
//            bfTitle = BaseFont.createFont("src/main/resources/templates/SourceHanSerifCN-Regular.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font fonttTitle;
            bfTitle = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);//创建字体
            fonttTitle = new Font(bfTitle, 18);
            fonttTitle.setStyle("bold");

            //表头部分
            BaseFont bf;
            Font font;
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);//创建字体
            font = new Font(bf, 12);//使用字体


            float[] widths = {10f, 25f, 10f, 40f, 15f};
            PdfPTable table = new PdfPTable(widths);
            table.setSpacingBefore(30f);
            table.setWidthPercentage(80);

            PdfPCell cellTitle;
            Paragraph card = new Paragraph("证据清单", fonttTitle);
            card.setSpacingBefore(30f);
            cellTitle = new PdfPCell(card);
            cellTitle.setHorizontalAlignment(Element.ALIGN_CENTER);
            cellTitle.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cellTitle.setColspan(5);
            cellTitle.setPaddingBottom(10f);
            cellTitle.setBorderWidth(0);
            table.addCell(cellTitle);


            String[] titles = new String[]{"编号", "证据名称", "份数", "证明对象", "形式"};
            PdfPCell cellt;
            for (String title : titles) {
                cellt = new PdfPCell(new Paragraph(title, font));
                setStyleData(cellt);
                table.addCell(cellt);
            }

            //以下代码的作用是创建100行数据,其中每行有四列,列依次为 编号 姓名 性别 备注
            for (int i = 1; i <= dataNums; i++) {
                //设置编号单元格
                PdfPCell cell11 = new PdfPCell(new Paragraph(i + "", font));
                PdfPCell cell22 = new PdfPCell(new Paragraph("bb女", font));
                PdfPCell cell33 = new PdfPCell(new Paragraph(1 + "", font));
                PdfPCell cell44 = new PdfPCell(new Paragraph("ccasdfghjksdfghjkllkjhgfdsasdfghjklkjhgfdsadfghj", font));
                PdfPCell cell55 = new PdfPCell(new Paragraph("复印件", font));

                setStyleData(cell11);
                setStyleData(cell22);
                setStyleData(cell33);
                setStyleData(cell44);
                setStyleData(cell55);

                table.addCell(cell11);
                table.addCell(cell22);
                table.addCell(cell33);
                table.addCell(cell44);
                table.addCell(cell55);
            }

            // 设置提交人位置
            for (int i = 1; i <= 3; i++) {
                PdfPCell cellBlank;
                for (int j = 0; j < 5; j++) {
                    if (i == 3 && j == 3) {
                        cellBlank = new PdfPCell(new Paragraph("提交人：", font));
                    } else {
                        cellBlank = new PdfPCell(new Paragraph("   ", font));
                    }
                    setStyleBlank(cellBlank);
                    table.addCell(cellBlank);
                }
            }

            document.add(table);
            document.close();
            byte[] bytes = b.toByteArray();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            savePdf(inputStream);

//            outputStream.write(bytes);
//            outputStream.flush();
//            outputStream.close();

            b.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private void setStyleBlank(PdfPCell cell) {
        cell.setFixedHeight(20);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setBorderWidth(0);

    }

    private void setStyleData(PdfPCell cell) {
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setFixedHeight(20);
    }


    public void savePdf(ByteArrayInputStream inputStream) throws IOException {
        byte[] b = new byte[inputStream.available()];
        inputStream.read(b);
        PDDocument pdDocument = PDDocument.load(b);
        PDFRenderer renderer = new PDFRenderer(pdDocument);
        int numberOfPages = pdDocument.getNumberOfPages();
        int heightSum = ((25) * (dataNums + 1)) + (24 * (3)) + 30 + 10 + 18 + ((numberOfPages - 1) * 100);
        int he = heightSum - ((numberOfPages - 1) * 1053);


        ByteArrayOutputStream temp;
        File file = new File(p);
        if (!file.exists()) {
            file.mkdirs();
        }
        for (int i = 0; i < numberOfPages; i++) {
            String path = p + i + ".jpg";
            BufferedImage image = renderer.renderImageWithDPI(i, 90);
            temp = new ByteArrayOutputStream();
            if (i == numberOfPages - 1) {
                // 债转第二张 要画个章子
                BufferedImage img = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
                // 得到画笔
                Graphics2D graphics = (Graphics2D) img.getGraphics();
                graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                // 背景
                graphics.drawImage(image, 0, 0, null);
                // 盖章
//                String signImageFilePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
                String signImageFilePath = "src/main/resources/OIP.jpeg";
                Image signImg = ImageIO.read(new File(signImageFilePath));
                graphics.drawImage(signImg, 480, he, 200, 200, null);
                ImageIO.write(img, "jpg", temp);
            } else {
                ImageIO.write(image, "jpg", temp);
            }
            byte[] bytes = temp.toByteArray();
            FileWriteUtil.canCreatFile(path);
            FileOutputStream outputStream = new FileOutputStream(path);
            outputStream.write(bytes);
            outputStream.flush();
            temp.close();
            outputStream.close();
        }
    }
}

